from fastapi import APIRouter, File, UploadFile, HTTPException, status
from fastapi.responses import JSONResponse
import os

router = APIRouter(prefix="/api/v1", tags=["文件上传"])

# 创建保存目录（如果不存在）
UPLOAD_DIR = "uploads/pdf"
os.makedirs(UPLOAD_DIR, exist_ok=True)

@router.post("/upload-pdf/", summary="上传PDF文件")
async def upload_pdf(file: UploadFile = File(...)):
    # 验证文件类型
    if file.content_type != "application/pdf":
        raise HTTPException(
            status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
            detail="仅支持PDF文件"
        )

    # 验证文件扩展名
    if not file.filename.lower().endswith(".pdf"):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="文件名必须以.pdf结尾"
        )

    # 保存文件
    file_path = os.path.join(UPLOAD_DIR, file.filename)
    try:
        contents = await file.read()
        with open(file_path, "wb") as f:
            f.write(contents)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件保存失败: {str(e)}"
        )
    finally:
        await file.close()

    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={
            "filename": file.filename,
            "saved_path": file_path,
            "size": f"{len(contents)/1024:.2f} KB"
        }
    )